<?php

namespace common\models;

use app\models\AdminLog;
use common\utils\XCache;
use Yii;

/**
 * This is the model class for table "links".
 *
 * @property string $id
 * @property string $name
 * @property string $url
 * @property string $sort
 * @property string $clicks
 * @property string $type
 * @property string $attach
 * @property integer $status
 * @property string $created_at
 */
class Links extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'links';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'url'], 'required'],
            [['sort', 'clicks', 'status', 'created_at'], 'integer'],
            [['type'], 'string'],
            [['name'], 'string', 'max' => 64],
            ['url', 'string', 'max' => 255],
            [['url'], 'url', 'defaultScheme' => 'http'],
            [['attach'], 'image', 'extensions' => 'jpeg, jpg, gif, png', 'maxSize' => 1 * 1024 * 1024]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '名称',
            'url' => '链接地址',
            'sort' => '排序',
            'clicks' => '点击次数',
            'type' => '链接类型',
            'attach' => '链接图片',
            'status' => '状态',
            'created_at' => '录入时间',
        ];
    }

    public function attributeHints()
    {
        return ['attach' => '链接类型为图片时才有效'];
    }

    public function behaviors()
    {
        $path = '/uploads/image/' . date('Ymd') . '/l' . time() . '[[pk]].[[extension]]';
        return [
            [
                'class' => '\yiidreamteam\upload\ImageUploadBehavior',
                'attribute' => 'attach',
                'filePath' => '@frontend/web' . $path,
                'fileUrl' => $path
            ],
        ];
    }

    public function beforeSave($insert)
    {
        if ($this->isNewRecord) {
            $this->created_at = time();
        }
        $this->sort < 0 || !$this->sort && $this->sort = 0;
        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($_FILES[$this->formName()]['name']['attach']) {
            $this->attach = $this->getImageFileUrl('attach');
            $this->updateAll(['attach' => $this->attach], ['id' => $this->id]);
        }
        if ($insert) {
            AdminLog::log("新添友情链接：" . $this->name, "create");
        } else {
            @unlink(iconv('UTF-8', 'GB2312', Yii::$aliases['@frontend'] . '/web' . $changedAttributes['attach']));
            AdminLog::log("更新友情链接：旧：" . $changedAttributes['name'] . "；新：" . $this->name);
        }
        XCache::linksDelete($this->type);
    }

    public function afterDelete()
    {
        parent::afterDelete();
        @unlink(iconv('UTF-8', 'GB2312', Yii::$aliases['@frontend'] . '/web' . $this->attach));
        AdminLog::log("删除友情链接：" . $this->name, "delete");
        XCache::linksDelete($this->type);
    }

    /**
     * @param string $type ='图片'|'文字'
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function items($type)
    {
        $list = static::find()
            ->select('name,url,attach')
            ->where("status=1 and type=:type", [":type" => $type])
            ->orderBy("sort asc,id asc")
            ->asArray()
            ->all();
        if ($type == '图片') {
            foreach ($list as $key => $item) {
                if ($item['attach']) {
                    $list[$key]['attach'] = Yii::getAlias('@frontendUrl') . $item['attach'];
                }
            }
        }
        return $list;
    }
}
